package com.lagou.utils.interceptor;

import com.alibaba.fastjson.JSON;
import com.lagou.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 自定义拦截器
 */
@Component(value = "customInterceptor")
@Slf4j
public class CustomInterceptor implements HandlerInterceptor {

    private static final Set<String> URI_SET = new HashSet<>(Arrays.asList("/custom/meet/map",
            "/custom/meet/page", "/custom/meet/test"));

    @Autowired
    @Qualifier(value = "redis")
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        response.setCharacterEncoding("utf-8");
        if (!URI_SET.contains(uri)) {
            return true;
        }
        log.info("the request just be intercepted !");
        response.setStatus(200);
        PrintWriter writer = response.getWriter();
        ResponseResult<Object> fail = ResponseResult.fail();
        fail.setContent("被拦截的地址");
        writer.write(JSON.toJSONString(fail));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
